<script setup lang="ts">
import { request } from '@/utils/http'
import type { AxiosResponse } from 'axios'
import b64toBlob from 'b64-to-blob'
import { showLoadingToast, showToast, type ActionSheetAction } from 'vant'
import { ref } from 'vue'

// 1. 修改头像
// 1.1 控制修改头像弹层的显示/隐藏
const showAvatarSheet = ref(false)
// 1.2 打开相册/相机
const onSelectAvatar = async (item: ActionSheetAction, i: number) => {
  // 隐藏弹层
  showAvatarSheet.value = false
  if (i === 0) {
    // 相册上传
    const res = await MKMK.pickerPhoto()
    console.log('相册上传', res)

    uploadImg(res)
  } else if (i === 1) {
    // 拍照上传
    console.log('拍照上传')
  }
}

async function uploadImg(res: string) {
  const fd = new FormData()
  const blob = b64toBlob(res, 'image/jpeg')
  fd.append('file', blob, Date.now() + '.jpeg')

  showLoadingToast({
    message: '正在上传',
    duration: 0,
    forbidClick: true
  })
  const temp = await request.post<MkResponse<{ avatar: string }>>('/member/profile/avatar', fd)
  showToast('头像上传成功')
  profile.value.avatar = temp.data.result.avatar

  const user = MKMK.queryUser()
  user.avatar = temp.data.result.avatar
  MKMK.updateUser(user)
}

const showSelectBirth = ref(false)

interface ResType {
  selectedValues: string[]
}

const confirmBirth = (res: ResType) => {
  console.log(res.selectedValues)
  profile.value.birthday = res.selectedValues.join('-')
  showSelectBirth.value = false
}

const showSelectArea = ref(false)
const list = MKMK.getAreaColumns()

const confirmArea = (res: ResType) => {
  console.log(res.selectedValues)
  profile.value.provinceCode = Number(res.selectedValues[0])
  profile.value.cityCode = Number(res.selectedValues[1])
  profile.value.countyCode = Number(res.selectedValues[2])
  const province = list.province_list[Number(res.selectedValues[0])]
  const city = list.city_list[Number(res.selectedValues[1])]
  const county = list.county_list[Number(res.selectedValues[2])]
  profile.value.fullLocation = `${province} ${city} ${county}`
  showSelectArea.value = false
}

const columns = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' }
]
const showSelectJob = ref(false)
const confirmSelectJob = (res: ResType) => {
  console.log(res.selectedValues[0])
  profile.value.profession = res.selectedValues[0]
  showSelectJob.value = false
}

const profile = ref<ProfileInfo>({} as ProfileInfo)

async function getProfile() {
  const res = await request.get<null, AxiosResponse<MkResponse<ProfileInfo>>>('member/profile')
  console.log(res.data.result)
  profile.value = res.data.result
  selectJob.value = [profile.value.profession]
  selectBirth.value = profile.value.birthday.split('-')
  console.log(profile.value.countyCode);
  selectArea.value = `${profile.value.countyCode}`
}

const selectJob = ref<string[]>([])
const selectBirth = ref(['2021', '01', '01'])
const selectArea = ref('110101')

const loading = ref(false)
const onSubmit = async () => {
  console.log(profile.value)
  // MKMK.vibrator()
  loading.value = true
  await request.put('member/profile', profile.value)
  loading.value = false
  const user = MKMK.queryUser()
  user.nickname = profile.value.nickname
  MKMK.updateUser(user)
  showToast({ message: '保存成功' })
}

getProfile()
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image
        round
        width="100"
        height="100"
        class="avatar-img"
        :src="profile.avatar"
        @click="showAvatarSheet = true"
      >
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>
    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field v-model="profile.account" label="账号" readonly></van-field>
      <van-field v-model="profile.nickname" label="昵称" placeholder="请输入昵称"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group v-model="profile.gender" :icon-size="16">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field
        label="生日"
        v-model="profile.birthday"
        readonly
        placeholder="请选择日期"
        @click="showSelectBirth = true"
      ></van-field>
      <van-field
        label="所在地"
        v-model="profile.fullLocation"
        readonly
        placeholder="请选择所在地"
        @click="showSelectArea = true"
      ></van-field>
      <van-field
        label="职业"
        v-model="profile.profession"
        readonly
        placeholder="请选择职业"
        @click="showSelectJob = true"
      ></van-field>
    </van-cell-group>

    <div class="submit">
      <van-button :loading="loading" round block type="primary" @click="onSubmit"> 保存资料 </van-button>
    </div>
    <van-action-sheet
      v-model:show="showAvatarSheet"
      :actions="[{ name: '选择照片' }, { name: '拍照' }]"
      @select="onSelectAvatar"
      cancel-text="取消"
      :style="{ paddingBottom: '20px' }"
    >
    </van-action-sheet>

    <van-popup v-model:show="showSelectBirth" position="bottom" round>
      <van-date-picker
        title="选择日期"
        v-model="selectBirth"
        @cancel="showSelectBirth = false"
        @confirm="confirmBirth"
      ></van-date-picker>
    </van-popup>

    <van-popup v-model:show="showSelectArea" position="bottom" round>
      <van-area
        title="所在地"
        v-model="selectArea"
        :area-list="list"
        @cancel="showSelectArea = false"
        @confirm="confirmArea"
      ></van-area>
    </van-popup>

    <van-popup v-model:show="showSelectJob" position="bottom" round>
      <van-picker
        title="职业"
        v-model="selectJob"
        :columns="columns"
        @cancel="showSelectJob = false"
        @confirm="confirmSelectJob"
      ></van-picker>
    </van-popup>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
